<div id="app" class="container-fluid" style="margin-bottom: 50px;max-width: 1080px;">
    <div class="_header"></div>
    <div class="_content" id="page-main">
        <div class="task-form task-container" v-cloak>
            <audio controls id="voice-player" style="display: none;"></audio>
            <audio controls id="audition-player" style="display: none;"></audio>
            <div class="task-right">
                <section class="voice-select">
                    <header class="header">
                        <i class="fa fa-user"></i> <span class="text">选择发音人：{{voicer}}</span>
                    </header>
                    <div class="content-box" id="choose-voice">
                        <div class="select-bar">
                            <ul>
                                <li v-for="g in voiceGroup" v-bind:class="{ active: g.id == curGroup }"
                                    v-on:click="changeGroup(g)">{{g.name}}
                                </li>
                            </ul>
                        </div>
                        <div class="select-content scrollbar">
                            <ul v-for="g in voiceGroup" v-show="g.id == curGroup"
                                v-bind:class="{currentGroup: g.id == curGroup}">
                                <li v-for="v in list" v-show="v.category_id == curGroup"
                                    v-bind:class="{active: v.name == voicer , currentVoice:v.name == voicer}"
                                    v-on:click="changeVoice(v)" v-on:dblclick="playVoice(v)">
                                    <h4>
                                        <span class="fa fa-play-circle player player-voice" v-if="v.name != playing"
                                              data-toggle="tooltip" data-placement="right" title="点击试听"
                                              v-on:click="playVoice(v)"></span>
                                        <span class="fa fa-pause-circle player playing" v-if="v.name == playing"
                                              data-toggle="tooltip" data-placement="right" title="点击试听"
                                              v-on:click="playVoice(v)"></span>
                                        {{v.name}}
                                        <small>{{v.label}}</small>
                                    </h4>

                                    <span class="fa fa-plus-square player" data-toggle="tooltip" data-placement="left"
                                          title="插入发音人到指定文本位置" v-on:click="insertVoiceTag(v)"></span>
                                    <span class="fa fa-tree player" data-toggle="tooltip" data-placement="left"
                                          title="发音人支持多音字"></span>
                                </li>
                                <li v-if="checkLength()"
                                    style="text-align: center;width: 100%;display: block;line-height: 70px;color: #a2a2a2;">
                                    该分类的发音人暂时还是空的
                                </li>
                            </ul>
                        </div>
                    </div>
                    <div class="select-bottom voice-speed-pitch">
                        <div class="form-title" style="margin-bottom: 0;">语速</div>
                        <div class="form-input">
                            <input id="speed" placeholder="-100 - 100" type="hidden" min="-100" max="100" step="1"
                                   :value="speed" data-color="#b52473" srs-none="true" class="srs">
                        </div>

                        <div class="form-title" style="margin-bottom:0;margin-top: 3px;">语调</div>
                        <div class="form-input">
                            <input id="pitch" placeholder="-100 - 100" type="hidden" min="-100" max="100" step="1"
                                   :value="pitch" data-color="#26c1b4" srs-none="true" class="srs">
                        </div>

                        <div class="form-input text-center" style="margin-top: 25px;">
                            <button type="button" data-toggle="tooltip" data-placement="top" title="恢复为系统推荐的发音人语速/语调"
                                    class="btn btn-sm btn-primary mr5" v-on:click="resetVoiceSettings">恢复默认
                            </button>
                        </div>
                    </div>
                </section>
                <section class="voice-setting">
                    <header class="header">
                        <i class="fa fa-align-justify"></i> <span class="text">合成选项</span>
                    </header>

                    <div class="content-box" style="padding-bottom: 0;">
                        <div class="form-title">配音模式</div>
                        <div class="form-input ad-format">
                            <button type="button" data-toggle="tooltip" data-placement="top" title="仅生成配音音频"
                                    class="btn btn-sm mr5 active">普通配音
                            </button>
                        </div>
                    </div>

                    <div class="content-box">
                        <div class="form-title">音频格式</div>
                        <div class="form-input ad-format">
                            <button type="button" data-toggle="tooltip" data-placement="top" title="mp3音频，体积小、压缩格式"
                                    class="btn btn-sm mr5" v-bind:class="{ active: format == 'mp3' }"
                                    v-on:click="changeFormat('mp3')">Mp3 (双声道)
                            </button>
                            <button type="button" data-toggle="tooltip" data-placement="top"
                                    title="wav音频，体积较大、高质无损格式（限免中)" class="btn btn-sm mr5"
                                    v-bind:class="{ active: format == 'wav' }" v-on:click="changeFormat('wav')">Wav
                                (双声道)
                            </button>
                            <button type="button" data-toggle="tooltip" data-placement="top"
                                    title="PCM音频，体积小、压缩格式" class="btn btn-sm mr5"
                                    v-bind:class="{ active: format == 'wav48' }" v-on:click="changeFormat('wav48')">PCM
                                (双声道)
                            </button>
                        </div>
                    </div>
                </section>
            </div>
            <div class="task-main">
                <div class="form-title">任务名称</div>
                <div class="form-input">
                    <input class="form-control inlineblock" style="width: 100%" type="text" id="name"
                           placeholder="50个字以内（非必填）">
                </div>
                <div class="form-title"></div>
                <div class="form-input" id="editer-tips">
                    <div class="bar-tool">
                        <div class="bar-block">
                            <label class="btn btn-sm label-tag insert" data-toggle="tooltip" data-placement="top"
                                   title="可在任意文本处插入停顿" @click="insertTag('stop')">停顿标签</label>
                            <label class="btn btn-sm label-tag insert" data-toggle="tooltip" data-placement="top"
                                   title="可以在任意文本处插入语速标签，达到更改语速的效果" @click="insertTag('speed')">语速标签</label>
                            <label class="btn btn-sm label-tag insert" data-toggle="tooltip" data-placement="top"
                                   title="可以在任意文本处插入语调标签，达到更改语调的效果" @click="insertTag('pitch')">语调标签</label>
                            <label class="btn btn-sm label-tag insert" data-toggle="tooltip" data-placement="top" title="使用别名来替换原始文本" @click="insertTag('alias')">别名标签</label>
                            <label class="btn btn-sm label-tag insert" data-toggle="tooltip" data-placement="top"
                                   title="快速处理多音字" @click="polyphoneHandle">多音字</label>
                        </div>

                        <div class="bar-block audition">
                            <button data-toggle="tooltip" data-placement="top" title="清除缓存文本" type="button"
                                    class="btn btn-sm btn-danger audition" @click="clearStorage">清除缓存
                            </button>
                            <button data-toggle="tooltip" data-placement="top"
                                    title="在线试听，主要用于实时调整语速语调及预览配音效果。目前试听不会消耗点数" type="button" id="audition-task"
                                    class="btn btn-sm btn-warning audition" @click="auditionTask" v-if="!tryListening">在线试听
                            </button>
                            <button data-toggle="tooltip" data-placement="top" title="停止试听" type="button"
                                    class="btn btn-sm btn-warning audition" @click="stopAuditionTask()" v-else><i class="fa fa-pause-circle"></i> 停止试听
                            </button>
                        </div>
                    </div>
                    <ul class="nav nav-tabs editer-bars">
                        <li role="presentation" class="active"><a href="javascript:;">配音编辑器</a></li>
                    </ul>
                    <div class="editer-content">
                        <div class="editer-tools" v-show="globalTag.textAlias.length > 0">
                            <div class="textalias-global" v-for="tag in globalTag.textAlias">
                                <span data-toggle="tooltip" data-placement="top" title="显示文本"><i class="fa fa-eye"></i> {{tag.originText}}</span><span data-toggle="tooltip" data-placement="top" title="阅读文本"><i class="fa fa-microphone-alt"></i> {{tag.readText}}</span>

                                <i class="fa fa-times-circle tool-close" data-toggle="tooltip" data-placement="top" title="移除全局别名标签" v-on:click="removeGlobalTextAlias(tag)"></i>
                            </div>
                        </div>
                        <div class="expandingTextArea" autoHeight="true">
                            <textarea class="form-control" id="content" rows="22" data-toggle="tooltip"
                                      data-placement="bottom" title="至少填入{$site.minInputNumber}个文字噢"
                                      placeholder="1.支持多发音人配音，可使用发音人标签，如：“{@艾夏}” “{@艾诚}” 切换配音发音人 &#13;&#10;2.支持停顿标签，如：“{1秒}” “{5秒}” “{100毫秒}” “{1500毫秒}”&#13;&#10;"
                                      v-on:input="inputTextNumber($event)"></textarea>
                        </div>
                    </div>
                    <p class="text-number">
                        总字数：
                        <span v-bind:class="{'text-number-red':useTextNumber > maxTextNumber}">
                            <span title="文本字数">{{useTextNumber}}</span> / <span
                                title="剩余字数">{{maxTextNumber - useTextNumber}}</span>
                        </span>

                        &nbsp;&nbsp;&nbsp;
                        <span data-toggle="tooltip" data-placement="top" title="本次任务预计消耗字符数">
                            <a style="color: #de1511;" target="_blank">
                                消费：{{ useTextNumber * price }}
                            </a>
                        </span>
                    </p>
                    <div class="clear"></div>
                </div>
                <div class="clear"></div>

                <div class="container-wrap-stop">
                    <div class="radio icheck-success warpstop-tips" data-toggle="tooltip" data-placement="top"
                         title="开启“换行停顿”后，系统将在文本换行处，自动增加停顿时间，默认为 1000 毫秒，即1秒">
                        <input type="checkbox" id="wrap-stop" name="wrap-stop" value="stop">
                        <label for="wrap-stop" class="icheck-sm">换行停顿</label>
                        <span class="stop-sec"><input class="form-control inlineblock" id="wrapstopSec" value="1000"
                                                      type="number" min="100" max="30000" placeholder="毫秒(ms)"
                                                      style="width: 100px;"> 毫秒</span>
                    </div>

                    <!--<div class="form-inline inlineblock tonepause-sec" data-toggle="tooltip" data-placement="top"-->
                    <!--     title="“语气停顿”指常见语气标点符号（逗号、句号等）的停顿时长，允许自定义时长">-->
                    <!--    <label>语气停顿</label>-->
                    <!--    <span><input class="form-control inlineblock" id="tonePauseSec" value="150" type="number"-->
                    <!--                 min="0" max="3000" placeholder="毫秒(ms)" style="width: 100px;"> 毫秒</span>-->
                    <!--</div>-->
                </div>
                <div class="form-submit">
                    <button type="button" class="btn btn-primary submit-task" v-on:click="submitTask(true)">提交&清空
                    </button>
                    <button type="button" class="btn btn-primary submit-task" v-on:click="submitTask()">提交任务</button>
                </div>
            </div>
        </div>
    </div>
</div>

<link rel="stylesheet" href="__CDN__/assets/css/page_index.css">
<link href="__CDN__/static/app/api/js/srs.css" rel="stylesheet">
<script src="__CDN__/assets/libs/jquery/dist/jquery.min.js"></script>
<script src="__CDN__/assets/libs/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script type="text/javascript" src="__CDN__/static/app/api/js/srs.reload.js"></script>
<script src="__CDN__/static/app/api/layui-v2.6.8/layui.js"></script>
<script src="__CDN__/static/app/api/js/addon_insert.js"></script>
<script src="__CDN__/static/app/api/js/pinyin.dict.js"></script>
<script src="//cdn.jsdelivr.net/npm/eruda"></script>

<script>
    eruda.init();
    $(function () {
        $("[data-toggle='tooltip']").tooltip();
    });

    $(".navTabs-Right .tabs-mb").click(function () {
        let $this = $(this);
        let show = $this.data("show");
        if (show) {
            $(".navTabs-Right .nav").fadeOut();
            $this.data("show" , "");
        } else {
            $(".navTabs-Right .nav").fadeIn();
            $this.data("show" , "true");
        }
    });
    $("body").click(function (e) {
        let tab = $(".navTabs-Right .tabs-mb");
        let is = $(e.target).parents().is("._nav");
        if (!is && tab.data("show")) {
            $(".navTabs-Right .nav").fadeOut();
            tab.data("show" , "");
        }
    });
</script>

<script>
    var chineseCharToPinyin = (function () {
        // 注意这里的变量 pinyinDict 来自于字典文件，需要先引入字典文件，且该变量不要在程序中被覆盖
        var temp = pinyinDict.split(','), withtone = {};
        // 循环遍历字典，以汉字字符为 key，对应的拼音为 value，形成一个超大的 JSON 对象
        for (var i = 0; i < temp.length; i++) {
            withtone[String.fromCharCode(i + 19968)] = temp[i];
        }
        var toneMap = {
            "ā": "a1", "á": "a2", "ǎ": "a3", "à": "a4", "ō": "o1", "ó": "o2", "ǒ": "o3",
            "ò": "o4", "ē": "e1", "é": "e2", "ě": "e3", "è": "e4", "ī": "i1", "í": "i2",
            "ǐ": "i3", "ì": "i4", "ū": "u1", "ú": "u2", "ǔ": "u3", "ù": "u4", "ü": "v0",
            "ǖ": "v1", "ǘ": "v2", "ǚ": "v3", "ǜ": "v4", "ń": "n2", "ň": "n3", "": "m2"
        };
        // 未开启声调识别的时候，将带声调的字符切换成不带声调的字母
        var removeTone = function (pinyin) {
            console.log(pinyin)
            return pinyin.replace(/[āáǎàōóǒòēéěèīíǐìūúǔùüǖǘǚǜńň]/g, function (m) {
                return toneMap[m];
            });
        };
        // 过滤掉多音字穷举产生的相同结果
        var simpleUnique = function (array) {
            var result = [], hash = {};
            for (var i = 0; i < array.length; i++) {
                var key = (typeof array[i]) + array[i];
                if (!hash[key]) {
                    result.push(array[i]);
                    hash[key] = true;
                }
            }
            return result;
        };
        // 多音字穷举
        var handlePolyphone = function (array, joinChar) {
            var result = [''], temp = [];
            for (var i = 0; i < array.length; i++) {
                temp = [];
                var t = array[i].split(' ');
                for (var j = 0; j < t.length; j++) {
                    for (var k = 0; k < result.length; k++)
                        temp.push(result[k] + (result[k] ? joinChar : '') + t[j]);
                }
                result = temp;
            }
            return simpleUnique(result);
        };
        // 对外返回一个转化的方法
        return function (str, isTone = false, isMultitone = false) {
            var result = [], pinyin;
            for (var i = 0; i < str.length; i++) {
                pinyin = withtone[str[i]];
                if (!isTone && pinyin) pinyin = removeTone(pinyin);
                if (!isMultitone && pinyin) pinyin = pinyin.replace(/ .*$/g, '');
                let tempPinyin = [];
                pinyin.split(" ").forEach(function (item){
                    tempPinyin.push(item.replace(/([a-z]+)([0-9])([a-z]+)/g,"$1$3$2"))
                })
                pinyin = tempPinyin.join(" ");
                result.push(pinyin || str[i]);
            }

            if (!isMultitone) return result.join(" ");
            return handlePolyphone(result, " ");
        }
    })();
    function aliasFormat(alias,content){
        for (let i in alias) {
            let tag = alias[i];
            content = content.replace(eval("/("+tag.originText+")/g"),tag.readText)
        }
        console.log(content)
        return content;
    }
</script>
<script>
    new Vue({
        el: '#app',
        data: {
            speed: localStorage.getItem("speed")?localStorage.getItem("speed"):0,
            pitch: localStorage.getItem("pitch")?localStorage.getItem("pitch"):0,
            voicer: localStorage.getItem("voicer")?localStorage.getItem("voicer"):"艾诚",
            voiceGroup: {$category},
            curGroup: localStorage.getItem("curGroup")?localStorage.getItem("curGroup"):{$selectCategoryId},
            list: {$list},
            playing: "",
            voiceParam: localStorage.getItem("voiceParam")??"aicheng",
            format: localStorage.getItem("format")??"mp3",
            useTextNumber: localStorage.getItem("useTextNumber")??0,
            maxTextNumber: {$site.maxTextNumber},
            price: {$site.price},
            defsTag: {
                tag_stop_val: 1,
                tag_stop_type: 's',
                tag_speed_val: 0,
                tag_pitch_val: 0,
                tag_alias_org_val: '',
                tag_alias_new_val: '',
            },
            playerVoice:{},
            tryListening:false,
            globalTag:{textAlias:[], /*全局别名标签 {originText:"" , readText:""}*/},
        },
        mounted() {
            this.globalTag = localStorage.getItem("textAlias") != null ? JSON.parse(localStorage.getItem("textAlias")) : {"textAlias": []};
            let $this = this;
            $this.$nextTick(()=>{
                $("#speed").srs();
                $("#pitch").srs();
            })
            this.initHandleClick();
            this.playerVoice = document.getElementById("voice-player");
            this.playerVoice.addEventListener('ended', function () {
                $this.playing = "";
                $this.tryListening = false;
            }, false);
            $("#name").val(localStorage.getItem("name")?localStorage.getItem("name"):"")
            $("#content").val(localStorage.getItem("content")?localStorage.getItem("content"):"")
            setInterval(()=>{
                let speed = $("#speed").val();
                let pitch = $("#pitch").val();
                let name = $("#name").val()
                localStorage.setItem("speed",speed)
                localStorage.setItem("pitch",pitch)
                localStorage.setItem("name",name)
                localStorage.setItem("textAlias",JSON.stringify($this.globalTag))
            },1000)
        },
        methods: {
            srsChange(e,v){
                console.log(e)
                console.log(v)
            },
            clearStorage(){
                $("#name").val("");
                $("#content").val("");
                $("#speed").val("");
                $("#pitch").val("");
                this.globalTag.textAlias = []
                localStorage.clear()
            },
            changeGroup(e) {
                this.curGroup = e.id
                localStorage.setItem("curGroup",e.id)
            },
            checkLength() {
                const _this = this;
                const result = this.list.some(function (item) {
                    return item.category_id == _this.curGroup
                })
                return !result
            },
            changeVoice(e) {
                this.voicer = e.name;
                this.voiceParam = e.param;
                localStorage.setItem("voicer",e.name)
                localStorage.setItem("voiceParam",e.param)
            },
            playVoice(e) {
                let $this = this;
                if (e) {
                    if($this.playerVoice.paused) {
                        $this.playerVoice.src = `__CDN__/static/voice/${e.param}.wav`;
                        $this.playerVoice.play();
                        $this.playing = e.name;
                    } else {
                        $this.playerVoice.pause();
                        if ($this.playing && e.name != $this.playing) {
                            $this.playVoice(e);
                        } else {
                            $this.playing = "";
                        }
                    }
                }
            },
            auditionTask(e){
                const $this = this;
                if(this.useTextNumber < {$site.minInputNumber|htmlentities}){
                    return layer.msg("最小配音字数为"+{$site.minInputNumber|htmlentities}, {icon: 5})
                }
                if($("input[name='wrap-stop']:checked").val() ? true : false){
                    if($("#wrapstopSec").val()<100 || $("#wrapstopSec").val() > 3000){
                        layer.msg("换行停顿时间超出范围，请保持在100~3000毫秒的范围",{icon:"5"});return;
                    }
                }
                layer.msg("正在试听，请稍等...")
                $.post("api/index/tempTask",{
                    voicer: this.voicer,
                    speed: $("#speed").val(),
                    pitch: $("#pitch").val(),
                    format: this.format,
                    name: $("#name").val(),
                    content: aliasFormat($this.globalTag.textAlias,$("#content").val()),
                    wrap_stop: $("input[name='wrap-stop']:checked").val() ? true : false,
                    wrap_stop_sec: $("#wrapstopSec").val(),
                },function(res){
                    if(res.code == '1'){
                        $this.playerVoice.src = res.data;
                        $this.playerVoice.play();
                        $this.tryListening = true;
                    }
                })
            },
            stopAuditionTask(){
                this.playerVoice.pause();
                this.tryListening = false;
            },
            resetVoiceSettings() {
                $("#speed").val(0);
                $("#pitch").val(0);
                $("#speed").srs();
                $("#pitch").srs();
            },
            changeFormat(e) {
                this.format = e
                localStorage.setItem("format",e)
            },
            inputTextNumber(e) {
                let contentValue = $.trim($("#content").val());
                localStorage.setItem("content",contentValue);
                contentValue = contentValue.replace(/[{]([0-9]+)秒[}]/g, '');
                contentValue = contentValue.replace(/[{]语速(-*[0-9]+)[}]/g, '');
                contentValue = contentValue.replace(/[{]语调(-*[0-9]+)[}]/g, '');
                contentValue = contentValue.replace(/\{别名#([a-zA-Z0-9\u4e00-\u9fa5]+)=([a-zA-Z0-9\u4e00-\u9fa5]+)}/g, '$2');
                contentValue = contentValue.replace(/\[pys\:([\u4e00-\u9fa5]+)\:([a-z]+[0-9])\]/, '$1');
                this.useTextNumber = contentValue.length;
                localStorage.setItem("useTextNumber",contentValue.length);

            },
            submitTask(isClear) {
                const $this = this;
                {if !$user}return layer.msg("请先登录再进行配音", {icon: 5});{/if}

                if($("input[name='wrap-stop']:checked").val() ? true : false){
                    if($("#wrapstopSec").val()<100 || $("#wrapstopSec").val() > 3000){
                        layer.msg("换行停顿时间超出范围，请保持在100~3000毫秒的范围",{icon:"5"});return;
                    }
                }

                if(this.useTextNumber < {$site.minInputNumber|htmlentities}){
                    return layer.msg("最小配音字数为"+{$site.minInputNumber|htmlentities}, {icon: 5})
                }
                {if $user}const userMoney = {$user['money']};{/if}

                if(userMoney < this.useTextNumber * this.price){
                    layer.msg("当前余额不足以完成此次配音",{icon:5});
                }else {
                    $.post("api/index/task",{
                        voicer: this.voicer,
                        speed: $("#speed").val(),
                        pitch: $("#pitch").val(),
                        format: this.format,
                        name: $("#name").val(),
                        content: aliasFormat($this.globalTag.textAlias,$("#content").val()),
                        wrap_stop: $("input[name='wrap-stop']:checked").val() ? true : false,
                        wrap_stop_sec: $("#wrapstopSec").val()
                    },function(res){
                        console.log(res)
                        if(res.code == 1){
                            layer.confirm('提交成功。是否前往查看任务进度？', {
                                btn: ['立即前往','取消']
                            }, function(){
                                //跳转到查看链接
                                location.href="{:url('index/user/task')}"
                            });
                        }else{
                            layer.msg(res.msg,{icon:5})
                        }
                    })
                }
            },
            insertTag(tag) {
                let $this = this;
                let html = $(`#tag-${tag}`).html();
                let title = $(`#tag-${tag}`).data("title");
                layui.layer.open({
                    type: 1,
                    area: ['380px', 'auto'],
                    offset: '30%',
                    title: title,
                    zIndex: 1000,
                    content: html
                });
                switch (tag) {
                    case "stop":
                        $("#tag_stop_val").val($this.defsTag.tag_stop_val);
                        $("#tag_stop_type").val($this.defsTag.tag_stop_type);
                        break;
                    case "speed":
                        $("#tag_speed_val").val($this.defsTag.tag_speed_val);
                        break;
                    case "pitch":
                        $("#tag_pitch_val").val($this.defsTag.tag_pitch_val);
                        break;
                    case "alias":
                        let selectWord = window.getSelection();
                        if ($.trim(selectWord) != "") {
                            $("#tag_alias_org_val").val(selectWord);
                            $("#tag_alias_new_val").val("");
                        } else {
                            $("#tag_alias_org_val").val($this.defsTag.tag_alias_org_val);
                            $("#tag_alias_new_val").val($this.defsTag.tag_alias_new_val);
                        }
                        break;
                }
            },
            insertVoiceTag(e) {
                const $this = this;
                console.log(e.name)
                $("#content").insertAtCaret(`{@${e.name}}`);
            },
            initHandleClick() {
                const $this = this;
                $("body").delegate(".tag-submit", "click", function () {
                    let tag = $(this).data("tag");
                    let v, vt;
                    let vs, vn, vg;
                    switch (tag) {
                        case "stop":
                            v = $("#tag_stop_val").val();
                            vt = $("#tag_stop_type").val();
                            v = parseInt(v);
                            if (vt == "s") {
                                if (v > 60) v = 60;
                                if (v < 0) v = 1;
                                $("#content").insertAtCaret(`{${v}秒}`);
                            } else {
                                if (v > 60000) v = 60000;
                                if (v < 10) v = 10;
                                $("#content").insertAtCaret(`{${v}毫秒}`);
                            }
                            $this.defsTag.tag_stop_val = v;
                            $this.defsTag.tag_stop_type = vt;
                            break;
                        case "speed":
                            v = parseInt($("#tag_speed_val").val());
                            if (v > 100) v = 100;
                            if (v < -100) v = -100;
                            $("#content").insertAtCaret(`{语速${v}}`);
                            $this.defsTag.tag_speed_val = v;
                            break;
                        case "pitch":
                            v = parseInt($("#tag_pitch_val").val());
                            if (v > 100) v = 100;
                            if (v < -100) v = -100;
                            $("#content").insertAtCaret(`{语调${v}}`);
                            $this.defsTag.tag_pitch_val = v;
                            break;
                        case "alias":
                            let global = $(this).data("global");
                            if (global == "yes") {
                                vg = true;
                            } else {
                                vg = false;
                            }
                            vs = $.trim($("#tag_alias_org_val").val());
                            vn = $.trim($("#tag_alias_new_val").val());
                            if (vs == "") {
                                layer.msg("原始文本不能为空");return;
                            }
                            if (vg) {
                                for (let i in $this.globalTag.textAlias) {
                                    if ($this.globalTag.textAlias[i].originText == vs) {
                                        layer.msg("全局别名规则已存在，不能重复添加哦");
                                        return;
                                    }
                                }
                                $this.globalTag.textAlias.push({originText:vs , readText:vn});
                                console.log($this.globalTag)
                            } else {
                                $("#content").insertAtCaret(`{别名#${vs}=${vn}}`);
                            }
                            $this.defsTag.tag_alias_org_val = vs;
                            $this.defsTag.tag_alias_new_val = vn;
                            break;
                    }
                    layer.closeAll("page");
                    console.log(tag)
                })
                $("body").delegate(".polyphone-container .pys", "click", function () {
                    let pys = $(this).data("pys");
                    let han = $(this).data("han");
                    if (!pys || !han) {
                        return;
                    }
                    $("#content").insertAtCaret(`[pys:${han}:${pys}]`);
                    layer.closeAll();
                });
            },
            removeGlobalTextAlias(tag) {
                let $this = this;

                for (let i in $this.globalTag.textAlias) {
                    if ($this.globalTag.textAlias[i].originText == tag.originText) {
                        $this.globalTag.textAlias.splice(i , 1);
                        break;
                    }
                }
            },
            polyphoneHandle() {
                let selectWord = $.trim(window.getSelection());
                if (selectWord == "") {
                    layer.msg("请选择要处理的多音字", {icon: 5})
                    return;
                }
                if (selectWord.length > 1) {
                    layer.msg("请选择一个多音字进行处理", {icon: 5})
                    $("#content").focus();
                    return;
                }
                if (!/^[\u4E00-\u9FA5]$/.test(selectWord)) {
                    layer.msg("请选择中文字符", {icon: 5})
                    $("#content").focus();
                    return;
                }
                // 处理多音字
                const pysphone = chineseCharToPinyin(selectWord, false, true)
                let pysHtml = `<span class="btn btn-sm btn-primary mr5 pys" data-pys="{pys}" data-han="{han}">{name}</span>`;
                let html = `<form class="tag-content">
                            <div class="polyphone-container">
                                {pys}
                            </div>
                        </form>`;
                let optionsHtml = "";
                for (let i in pysphone) {
                    optionsHtml += pysHtml.replace(/{name}/g, pysphone[i]).replace(/{pys}/g, pysphone[i]).replace(/{han}/g, selectWord);
                }
                html = html.replace(/{pys}/, optionsHtml);
                layer.open({
                    type: 1,
                    skin: 'layui-layer-demo',
                    title: selectWord,
                    closeBtn: 1,
                    area: ['380px', '180px'],
                    anim: 2,
                    shadeClose: true,
                    content: html
                });
                $("#content").focus();
            },
        }
    })
</script>
<!-- 停顿标签 -->
<template id="tag-stop" data-title="停顿标签">
    <form class="tag-content">
        <div class="form-group">
            <label for="tag_stop_val">停顿时间</label>
            <div>
                <input type="number" class="form-control inlineblock" value="1" id="tag_stop_val" placeholder="停顿时间"
                       style="width: calc(100% - 90px);">
                <select class="form-control inlineblock" id="tag_stop_type" style="width:80px;">
                    <option value="s" selected>秒</option>
                    <option value="ms">毫秒</option>
                </select>
            </div>
        </div>
        <button type="button" class="btn fr btn-success tag-submit" data-tag="stop">插入</button>
        <div class="clear"></div>
    </form>
</template>

<!--语速标签-->
<template id="tag-speed" data-title="语速标签">
    <form class="tag-content">
        <div class="input-group" style="width: 85%;margin: 0 auto;margin-bottom: 8px;">
            <span class="input-group-addon pointer"
                  onclick="$('#tag_speed_val').val(Number($('#tag_speed_val').val()) - 1);"><i class="fa fa-minus"></i></span>
            <input type="number" class="form-control" placeholder="语速，-100 ~ 100" value="0" id="tag_speed_val" max="100"
                   min="-100">
            <span class="input-group-addon pointer"
                  onclick="$('#tag_speed_val').val(Number($('#tag_speed_val').val()) + 1);"><i
                    class="fa fa-plus"></i></span>
        </div>

        <button type="button" class="btn fr btn-success tag-submit" data-tag="speed">插入</button>
        <div class="clear"></div>
    </form>
</template>

<!--语调标签-->
<template id="tag-pitch" data-title="语调标签">
    <form class="tag-content">
        <div class="input-group" style="width: 85%;margin: 0 auto;margin-bottom: 8px;">
            <span class="input-group-addon pointer"
                  onclick="$('#tag_pitch_val').val(Number($('#tag_pitch_val').val()) - 1);"><i class="fa fa-minus"></i></span>
            <input type="number" class="form-control" placeholder="语调，-100 ~ 100" value="0" id="tag_pitch_val" max="100"
                   min="-100">
            <span class="input-group-addon pointer"
                  onclick="$('#tag_pitch_val').val(Number($('#tag_pitch_val').val()) + 1);"><i
                    class="fa fa-plus"></i></span>
        </div>
        <button type="button" class="btn fr btn-success tag-submit" data-tag="pitch">插入</button>
        <div class="clear"></div>
    </form>
</template>

<!--别名标签-->
<template id="tag-alias" data-title="别名标签">
    <form class="tag-content">
        <div class="form-group">
            <label for="tag_alias_org_val">显示文本</label>
            <input type="text" class="form-control inlineblock" value="" id="tag_alias_org_val"
                   placeholder="显示文本，不能包含标点符号">
        </div>
        <div class="form-group">
            <label for="tag_alias_new_val">阅读文本</label>
            <input type="text" class="form-control inlineblock" value="" id="tag_alias_new_val"
                   placeholder="阅读文本，不能包含标点符号">
        </div>

        <div class="text-right">
            <button type="button" class="btn btn-primary tag-submit" data-tag="alias" data-global="yes">全局设置</button>
            <button type="button" class="btn btn-success tag-submit" data-tag="alias" data-global="no">插入别名</button>
        </div>
        <div class="clear"></div>
    </form>
</template>